#include "app_context.h"
#include "com/simple_logger.h"

AppContext *AppContext::instance_ = new AppContext;

void AppContext::LoadAliasTable(std::string alias_table_prop)
{
    ctx_mtx_.lock();
    Properties p;
    if (p.Init(alias_table_prop.c_str()))
    {
        alias_table_prop_ = alias_table_prop;
        int size = p.size();
        for (int i = 0; i < size; i++)
        {
            online_table_->Insert(p.Key(i), p.Val(i));
        }
        LOG4CPLUS_DEBUG(SimpleLogger::Get()->LoggerRef(), "用户名别名表(alias table)载入完成");
    }
    else
    {
        LOG4CPLUS_ERROR(SimpleLogger::Get()->LoggerRef(), "缺少用户名别名表(alias table)");
    }
    ctx_mtx_.unlock();
}

std::string AppContext::GetAndReloadAlias(std::string key)
{

    if (online_table_->size() == 0)
    {
        return "";
    }
    OnlineItem *item = online_table_->FindByUsername(key);
    if (item)
    {
        return item->alias;
    }
    this->LoadAliasTable(alias_table_prop_);
    item = online_table_->FindByUsername(key);
    if (item)
    {
        return item->alias;
    }
    LOG4CPLUS_WARN(SimpleLogger::Get()->LoggerRef(), "未找到当前用户的别名(alias)");
    return "";
}

void AppContext::RegistService(std::string service_name)
{
    online_table_->Insert(service_name, service_name, true);
}

std::string AppContext::GetUsername(std::string alias)
{
    if (online_table_->size() == 0)
    {
        return "";
    }
    OnlineItem *item = online_table_->FindByAlias(alias);
    if (item)
    {
        return item->username;
    }
    this->LoadAliasTable(alias_table_prop_);
    item = online_table_->FindByAlias(alias);
    if (item)
    {
        return item->username;
    }
    LOG4CPLUS_WARN(SimpleLogger::Get()->LoggerRef(), "未找到当前用户名");
    return "";
}

bool AppContext::UserOnLine(unsigned int user_id, std::string user_alias)
{
    return online_table_->Online(user_id);
}

void AppContext::UserOffLine(unsigned int user_id)
{
    online_table_->Offline(user_id);
}

std::map<unsigned int, std::string> AppContext::online_table()
{
    return online_table_->GetOnlineTableRef();
}